// 企业控制器
package org.example.backend.controller;

import jakarta.validation.Valid;
import org.example.backend.dto.CompanyDto;
import org.example.backend.entity.Company;
import org.example.backend.entity.User;
import org.example.backend.exception.BusinessException;
import org.example.backend.service.CompanyService;
import org.example.backend.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/company")
@CrossOrigin
@PreAuthorize("hasRole('COMPANY')")
public class CompanyController {

    private static final Logger logger = LoggerFactory.getLogger(CompanyController.class);

    private final CompanyService companyService;
    private final UserService userService;

    public CompanyController(CompanyService companyService, UserService userService) {
        this.companyService = companyService;
        this.userService = userService;
    }

    /**
     * 企业注册（完善企业信息）
     */
    @PostMapping("/register")
    public ResponseEntity<?> registerCompany(@Valid @RequestBody CompanyDto companyDto) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 创建企业信息
            Company company = companyService.createCompany(companyDto, user.getId());

            Map<String, Object> response = new HashMap<>();
            response.put("message", "企业信息注册成功，等待管理员审核");
            response.put("company", company);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("企业注册失败", e);
            return ResponseEntity.badRequest().body("注册失败：" + e.getMessage());
        }
    }

    /**
     * 更新企业信息
     */
    @PutMapping("/profile")
    public ResponseEntity<?> updateCompany(@Valid @RequestBody CompanyDto companyDto) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取企业信息
            Company existingCompany = companyService.getCompanyByUserId(user.getId());

            // 更新企业信息
            Company company = companyService.updateCompany(existingCompany.getId(), companyDto);

            Map<String, Object> response = new HashMap<>();
            response.put("message", "企业信息更新成功");
            response.put("company", company);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("更新企业信息失败", e);
            return ResponseEntity.badRequest().body("更新失败：" + e.getMessage());
        }
    }

    /**
     * 获取企业个人信息
     */
    @GetMapping("/profile")
    public ResponseEntity<?> getCompanyProfile() {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取企业信息
            Company company = companyService.getCompanyByUserId(user.getId());

            return ResponseEntity.ok(company);
        } catch (Exception e) {
            logger.error("获取企业信息失败", e);
            return ResponseEntity.badRequest().body("获取信息失败：" + e.getMessage());
        }
    }

    /**
     * 提交企业信息审核
     */
    @PostMapping("/submit-review")
    public ResponseEntity<?> submitForReview() {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取企业信息
            Company existingCompany = companyService.getCompanyByUserId(user.getId());

            // 提交审核
            Company company = companyService.submitForReview(existingCompany.getId());

            Map<String, Object> response = new HashMap<>();
            response.put("message", "企业信息已提交审核");
            response.put("company", company);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("提交审核失败", e);
            return ResponseEntity.badRequest().body("提交审核失败：" + e.getMessage());
        }
    }
}
